﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.cms.presentation.Trees;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using Core.Module.Interfaces.Model;

namespace Core.Module.Manager
{
    public class LogManager : BaseTree,IApplicationTree 
    {
        private const string _applicationName = "ism-modules";
        public LogManager() : base(_applicationName) { }
        public LogManager(string application) : base(application) { }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            rootNode.NodeType = "init" + this.TreeAlias;
            rootNode.NodeID = "init";
            int amount = GetLogAmount("");
            RootNode.Text = "Site Log Info " + (amount > 0 ? " -(" + amount.ToString() + ")" : "");
            rootNode.Action = "javascript:openLogs()";

        }
        protected override void CreateAllowedActions(ref List<IAction> actions)
        {
            actions.Clear();
            //actions.Add(ActionNew.Instance);
            //actions.Add(ActionDelete.Instance);
            actions.Add(umbraco.BusinessLogic.Actions.ContextMenuSeperator.Instance);
            actions.Add(umbraco.BusinessLogic.Actions.ActionRefresh.Instance);
        }


        public override void Render(ref XmlTree tree)
        {
            if (string.IsNullOrEmpty(base.NodeKey) || base.NodeKey.Equals("init"))
            {
                RenderDateFilterSections(ref tree, null);
                RenderFirstLevelNodes(ref tree);
            }
            else
            {
                umbraco.BusinessLogic.LogTypes t;
                if (Enum.TryParse<umbraco.BusinessLogic.LogTypes>(base.NodeKey, out t))
                {//get child logs for section
                    RenderDateFilterSections(ref tree, t);
                }
            }

        }

        private void RenderDateFilterSections(ref XmlTree tree, umbraco.BusinessLogic.LogTypes? logTp)
        {
            Type t = typeof(umbraco.BusinessLogic.LogTypes);
            string filter = "";
            string typename = logTp != null ? Enum.GetName(t, logTp) : "";
            if (logTp != null) filter = "(logHeader='" + typename + "') and ";
            //today
            GenerateDateNode("Today", "today", GetLogAmount(filter: filter + " (Datestamp>@today)"), typename, ref tree);
            //1 day ago
            GenerateDateNode("Previos Day Logs", "day1", GetLogAmount(filter: filter + " (Datestamp>@day1)"), typename, ref tree);
            //2 days ago
            GenerateDateNode("2 Days Logs", "day2", GetLogAmount(filter: filter + " (Datestamp>@day2)"), typename, ref tree);
            //3 days ago
            GenerateDateNode("3 Days Logs", "day3", GetLogAmount(filter: filter + " (Datestamp>@day3)"), typename, ref tree);
            //1 week ago
            GenerateDateNode("Last Week Logs", "week1", GetLogAmount(filter: filter + " (Datestamp>@week1)"), typename, ref tree);
            ////2 week ago
            //GenerateDateNode("Last 2 Weeks Logs", "week2", GetLogAmount(filter: filter + " (Datestamp>@week2)"), typename, ref tree);
            //1 month ago
            GenerateDateNode("Last Month Logs", "month1", GetLogAmount(filter: filter + " (Datestamp>@month1)"), typename, ref tree);
            //3 month ago
            GenerateDateNode("Last Quarter Logs", "quarter1", GetLogAmount(filter: filter + " (Datestamp>@month3)"), typename, ref tree);
            //1 year ago
            GenerateDateNode("Last Year Logs", "year1", GetLogAmount(filter: filter + " (Datestamp>@year1)"), typename, ref tree);
        }

        private void GenerateDateNode(string name, string id, int amount, string section, ref XmlTree tree)
        {
            if (amount < 1) return;
            XmlTreeNode node = XmlTreeNode.Create(this);

            node.NodeID = id + "_" + section;
            node.Text = name + " - (" + amount.ToString() + ")";
            node.Action = string.Format("javascript:openLogSectionItem('{0}','{1}','');", section, id);
            node.NodeType = "LogSection";
            node.Source = base.GetTreeServiceUrl(name);
            node.HasChildren = false;
            node.Icon = "logsection_date.png";
            node.OpenIcon = "logsection_date_o.png";
            this.OnBeforeNodeRender(ref tree, ref node, EventArgs.Empty);
            if (node != null)
            {
                tree.Add(node);
                this.OnAfterNodeRender(ref tree, ref node, EventArgs.Empty);
            }
        }


        private void RenderFirstLevelNodes(ref XmlTree tree)
        {
            Type t = typeof(umbraco.BusinessLogic.LogTypes);

            foreach (Int32 item in Enum.GetValues(t))
            {
                string logSectionName = Enum.GetName(t, item);
                int amount = GetLogAmount(filter: "(logHeader='" + logSectionName + "')");
                if (amount > 0)
                {
                    XmlTreeNode node = XmlTreeNode.Create(this);

                    node.NodeID = item.ToString();
                    node.Text = logSectionName + " - (" + amount.ToString() + ")";
                    node.Action = string.Format("javascript:openLogSectionItem('{0}','{1}','{2}');", logSectionName, "", "");
                    node.NodeType = "LogSection";
                    node.Source = base.GetTreeServiceUrl(item.ToString());
                    node.HasChildren = false;
                    node.Icon = "logsection.png";
                    node.OpenIcon = "logsection_o.png";
                    this.OnBeforeNodeRender(ref tree, ref node, EventArgs.Empty);
                    if (node != null)
                    {
                        tree.Add(node);
                        this.OnAfterNodeRender(ref tree, ref node, EventArgs.Empty);
                    }
                }
            }
        }




        public override void RenderJS(ref StringBuilder Javascript)
        {
            Javascript.Append("\r\n\t\t\tfunction openLogSectionItem(logid,period,pagesize) {\r\n\t\t\t\t");
            Javascript.Append("UmbClientMgr.contentFrame('ism/logoverview.aspx?selLogCategory=' + logid+'&pagesize='+pagesize+'&period='+period);");
            Javascript.Append("\r\n\t\t\t}\r\n\t\t\t");
            Javascript.Append("\r\n\t\t\tfunction openLogs() {\r\n\t\t\t\t");
            Javascript.Append("UmbClientMgr.contentFrame('ism/logoverview.aspx?selLogCategory=&pagesize=&period=');");
            Javascript.Append("\r\n\t\t\t}\r\n\t\t\t");
        }

        private int GetLogAmount(string filter)
        {
            string commandText = "select count(*) from umbracoLog {0}";
            string whereText = string.IsNullOrEmpty(filter) ? "" : string.Format(" where {0}", filter);
            try
            {
                Int32 res = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<Int32>(string.Format(commandText, whereText), GenerateParams(umbraco.BusinessLogic.Application.SqlHelper));
                return res;
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, -10, "GetLogAmount,Ism.Main.UComponents.legacy.Trees.LogTree." + ex.Message);
            }
            return -1;

        }

        private IParameter[] GenerateParams(ISqlHelper sqlHelper)
        {
            List<IParameter> rslt = new List<IParameter>();
            //dates
            rslt.Add(sqlHelper.CreateParameter("@today", DateTime.Today));
            rslt.Add(sqlHelper.CreateParameter("@day1", DateTime.Today.AddDays(-1)));
            rslt.Add(sqlHelper.CreateParameter("@day2", DateTime.Today.AddDays(-2)));
            rslt.Add(sqlHelper.CreateParameter("@day3", DateTime.Today.AddDays(-3)));
            rslt.Add(sqlHelper.CreateParameter("@week1", DateTime.Today.AddDays(-7)));
            rslt.Add(sqlHelper.CreateParameter("@week2", DateTime.Today.AddDays(-14)));
            rslt.Add(sqlHelper.CreateParameter("@month1", DateTime.Today.AddDays(-30)));
            rslt.Add(sqlHelper.CreateParameter("@month3", DateTime.Today.AddDays(-90)));
            rslt.Add(sqlHelper.CreateParameter("@year1", DateTime.Today.AddYears(-1)));
            return rslt.ToArray();
        }


        public string Alias
        {
            get { return "LogManager"; }
        }

        public string Application
        {
            get { return _applicationName; }
        }

        public string Icon
        {
            get { return "logmanager.png"; }
        }

        public string IconOpen
        {
            get { return "logmanager.png"; }
        }


        public byte OrderNr
        {
            get { return 255; }
        }
    }
}
